const { Room, RoomTag } = require('../models');
const { Op } = require('sequelize');
const { Coupon, User, Order, sequelize } = require('../models');
// 打印模型以检查是否正确引入
console.log('Room模型加载状态:', Room ? '已加载' : '未加载');
console.log('RoomTag模型加载状态:', RoomTag ? '已加载' : '未加载');

/**
 * 获取房间列表
 * 支持分页和筛选
 */
const getRoomList = async (req, res) => {
  try {
    console.log('[房间列表] 请求参数:', req.query);

    // 查询参数
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 10;
    const offset = (page - 1) * limit;
    
    // 构建查询条件
    const whereCondition = {};
    
    // 只有在有明确要求时才筛选状态
    if (req.query.status) {
      whereCondition.status = req.query.status;
    }
    
    // 如果有标签筛选
    if (req.query.tag) {
      // 通过关联表查询标签
      whereCondition['$tags.tag_name$'] = req.query.tag;
    }

    console.log('[房间列表] 查询条件:', JSON.stringify(whereCondition));

    // 查询房间列表，包含标签数据
    const rooms = await Room.findAndCountAll({
      where: whereCondition,
      include: [
        {
          model: RoomTag,
          as: 'tags',
          attributes: ['tag_name'],
          required: false
        }
      ],
      order: [
        ['id', 'ASC'] // 按照ID排序
      ],
      limit,
      offset,
      distinct: true // 避免多标签时重复计数
    });
    
    console.log('[房间列表] 查询结果数量:', rooms.count);
    
    // 处理返回的数据结构，将标签转换为字符串数组
    const formattedRooms = rooms.rows.map(room => {
      const roomData = room.toJSON();
      roomData.tags = roomData.tags ? roomData.tags.map(tag => tag.tag_name) : [];
      return roomData;
    });
    
    // 构建分页信息
    const pagination = {
      total: rooms.count,
      page,
      limit,
      totalPages: Math.ceil(rooms.count / limit)
    };

    // 返回结果
    res.status(200).json({
      code: 200,
      message: rooms.count > 0 ? '获取房间列表成功' : '暂无房间数据',
      data: {
        rooms: formattedRooms,
        pagination
      }
    });
  } catch (error) {
    console.error('获取房间列表失败:', error);
    res.status(500).json({
      code: 500,
      message: '获取房间列表失败，请稍后重试',
      data: null,
      error: error.message
    });
  }
};

/**
 * 获取房间详情
 */
const getRoomDetail = async (req, res) => {
  try {
    const { id } = req.params;

    // 查询房间信息，暂时不包含标签
    const room = await Room.findOne({
      where: {
        id,
        status: 'available' // 修改为status字段的实际值
      }
      // 暂时注释掉include
      /*
      include: [
        {
          model: RoomTag,
          as: 'tags',
          attributes: ['tag_name']
        }
      ]
      */
    });
    
    if (!room) {

      return res.status(404).json({
        code: 404,
        message: '房间不存在或已禁用',
        data: null
      });
    }
    
    // 处理返回的数据结构
    const roomData = room.toJSON();
    // 暂时设置为空数组
    roomData.tags = [];

    // 返回房间详情
    res.status(200).json({
      code: 200,
      message: '获取房间详情成功',
      data: {
        room: roomData
      }
    });
  } catch (error) {
    console.error('获取房间详情失败:', error);
    res.status(500).json({
      code: 500,
      message: '获取房间详情失败，请稍后重试',
      data: null
    });
  }
};
/**
 * 获取优惠券可选房间列表
 * 支持分页和筛选
 */
const getCouponRoomList = async (req, res) => {
  try {
    console.log('[优惠券可选房间列表] 请求参数:', req.query);

    // 查询参数
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 10;
    const offset = (page - 1) * limit;
    const couponId = parseInt(req.query.couponId); // 从查询参数中获取优惠券ID
  
    //查询优惠券信息
    const coupon = await Coupon.findOne({
      where: {
        id: couponId,
        isTemplate: false // 只查询模板券
      }
    });
    if (!coupon) {
      return res.status(404).json({
        code: 404,
        message: '优惠券不存在',
        data: null
      });
    }
     // 构建查询条件
    const whereCondition = {};
    
     // 如果有标签筛选
    if (req.query.tag) {
       // 通过关联表查询标签
      whereCondition['$tags.tag_name$'] = req.query.tag;
    }
    whereCondition.roomType = coupon.roomType;
    whereCondition.status = 'available';
    console.log('[房间列表] 查询条件:', JSON.stringify(whereCondition));
    // 查询房间列表，包含标签数据
    const rooms = await Room.findAndCountAll({
      where: whereCondition,
      include: [
        {
          model: RoomTag,
          as: 'tags',
          attributes: ['tag_name'],
          required: false
        }
      ],
      order: [
        ['id', 'ASC'] // 按照ID排序
      ],
      limit,
      offset,
      distinct: true // 避免多标签时重复计数
    });
    
    console.log('[房间列表] 查询结果数量:', rooms.count);
    
    // 处理返回的数据结构，将标签转换为字符串数组
    const formattedRooms = rooms.rows.map(room => {
      const roomData = room.toJSON();
      roomData.tags = roomData.tags ? roomData.tags.map(tag => tag.tag_name) : [];
      return roomData;
    });
    const duration = coupon.duration;
    // 构建分页信息
    const pagination = {
      total: rooms.count,
      page,
      limit,
      totalPages: Math.ceil(rooms.count / limit)
    };

    // 返回结果
    res.status(200).json({
      code: 200,
      message: rooms.count > 0 ? '获取房间列表成功' : '暂无房间数据',
      data: {
        rooms: formattedRooms,
        pagination,
        duration
      }
    });
  } catch (error) {
    console.error('获取房间列表失败:', error);
    res.status(500).json({
      code: 500,
      message: '获取房间列表失败，请稍后重试',
      data: null,
      error: error.message
    });
  }
};


module.exports = {
  getRoomList,
  getRoomDetail,
  getCouponRoomList
}; 